//index.js
//获取应用实例
var app = getApp()
import {
  getCheckCart,
  getCartCouponNum,
  chooseCoupon
} from '../../api/cart'
import {
  getAddress
} from '../../api/address'
import {
  createTrade,
  shippingAddress
} from '../../api/order'
var isDealer = 0
Page({
  data: {
    goodsList: [],
    isNeedLogistics: 0, // 是否需要物流信息
    allGoodsPrice: 0,
    yunPrice: 0,
    allGoodsAndYunPrice: 0,
    yuanTotal: 0,
    goodsJsonStr: "",
    orderType: "", //订单类型，购物车下单或立即支付下单，默认是购物车，
    curAddressData: null,
    dealer: null,
    hasNoCoupons: true,
    youhuijine: 0, //优惠券金额
    curCoupon: null, // 当前选择使用的优惠券
    dealerId: '',
    isDealerGoods: 0,
    BuyBatch: 0,
    isValid: 0,
    items: [{
      value: 1,
      name: '微信支付',
      checked: 'true'
    }],
    payType: 1,
    firstChange: true,
    coupon: null,
    newAdd: false,
    couponNum: 0,
    zongNum: 0
  },
  async onShow() {
    let that = this
    if( !that.data.newAdd ){
      that.initShippingAddress()
    }
    
    let type = this.data.orderType
    let res = await getCheckCart(type, wx.getStorageSync('access_token'))
    console.log(res)
    if (res && res.code == 10000) {
      let list = res.data.cartList[0].checkedSkuList.map(item => {
        return {
          active: item.checked,
          checkNum: false,
          pic: item.goodsSku.original,
          name: item.goodsSku.goodsName,
          id: item.goodsSku.id,
          number: item.num,
          label: item.goodsSku.simpleSpecs,
          price: item.goodsSku.vipPrice ? item.goodsSku.vipPrice : item.goodsSku.price,
          standardId: item.goodsSku.id
        }
      })
      let total = 0
      let zongNum = 0
      let yuanTotal = res.data.cartList[0].priceDetailVO.originalPrice
      total = res.data.cartList[0].priceDetailVO.finalPrice
      console.log(yuanTotal, total)
      for (let i in list) {
        zongNum += list[i].number
      }
      this.setData({
        zongNum
      })
      console.log(zongNum)
      this.setData({
        couponNum: res.data.canUseCoupons.length
      })
      this.setData({
        goodsList: list,
        allGoodsPrice: total,
        allGoodsAndYunPrice: this.data.allGoodsAndYunPrice == 0 ? total : this.data.allGoodsAndYunPrice,
        youhuijine: res.data.cartList[0].priceDetailDTO.discountPrice + res.data.cartList[0].priceDetailDTO.couponPrice,
        canUseCoupons: res.data.canUseCoupons,
        cantUseCoupons: res.data.cantUseCoupons,
        yuanTotal: yuanTotal,
      })
    }
    //显示收货地址标识
    // app.get('dealer/get_dealer_by_custid?CustId=' + app.globalData.uid, res => {
    //   console.log(res)
    //   if (res.code == 0) {
    //     if( res.result && res.result.IsValid == 1 ){
    //       this.setData({
    //         isValid: 1
    //       })
    //       isDealer = 1
    //       console.log(this.data.isValid)
    //     }else{
    //       this.setData({
    //         isValid: 0
    //       })
    //       isDealer = 0
    //     }
    //   }
    // })

    //console.log(this.data.orderType)
    // app.get('dealer/get_dealer_by_custid?CustId=' + app.globalData.uid, res => {
    //   if (res.result) {
    //     this.setData({
    //       dealerId: res.result.Id
    //     })
    //   }
    // })
    // if( wx.getStorageSync('dealerInfo') ) {
    //   this.setData({
    //     dealer: wx.getStorageSync('dealerInfo')
    //   })
    // }
  },

  async onLoad(e) {
    //console.log(e)
    var that = this;
    console.log(e)
    wx.hideShareMenu()
    if (app.globalData.iphone == true) {
      that.setData({
        iphone: 'iphone'
      })
    }
    //显示收货地址标识
    that.setData({
      isNeedLogistics: 1,
      orderType: e.orderType
    })
    if (e.id == null) {
      this.setData({
        newAdd: false
      })
    }
    // let res = await getCartCouponNum(e.orderType, wx.getStorageSync('access_token'))
    // console.log(res)
    // if (res && res.code == 10000) {
    //   this.setData({
    //     couponNum: res.data
    //   })
    // }
    // wx.getStorage({
    //   key: 'orderDetail',
    //   success(res) {
    //     shopList = JSON.parse(res.data);
    //     let total = 0;
    //     let IsDealerGoods=1;
    //     for (let i in shopList) {
    //       total += Number(shopList[i].number) * Number(shopList[i].price);
    //       // console.log(shopList[i]);
    //       if(shopList[i].IsDealerGoods==0){
    //         IsDealerGoods=0; 
    //       }
    //     }
    //     // if(IsDealerGoods==1){
    //     //   that.data.items.push({value: 2, name: '对公账号'});
    //     // }
    //     that.setData({
    //       isDealerGoods:IsDealerGoods,
    //       items:that.data.items
    //     })
    //     // console.log(shopList)
    //     that.setData({
    //       goodsList: shopList,
    //       allGoodsPrice: total.toFixed(2),
    //       allGoodsAndYunPrice: total.toFixed(2)
    //     });
    //     console.log(shopList)
    //   }
    // })
  },
  takeCoupon() {
    // if(this.data.couponNum < 1){
    //   wx.showToast({
    //     title: '暂无可用优惠券',
    //     icon: 'none'
    //   })
    //   return
    // }
    console.log(this.data.goodsList);
    var ids = this.data.goodsList.map(item => item.id).join(",")
    let coupon = this.data.coupon ? '&couponId=' + this.data.coupon.id : ''
    console.log(ids);
    wx.navigateTo({
      url: '/pages/coupons/coupons2?cantCoupons=' + JSON.stringify(this.data.cantUseCoupons) + '&canCoupons=' + JSON.stringify(this.data.canUseCoupons) + '&orderType=' + this.data.orderType + coupon,
    })
  },
  getDistrictId: function (obj, aaa) {
    if (!obj) {
      return "";
    }
    if (!aaa) {
      return "";
    }
    return aaa;
  },
  radioChange(e) {
    if (e.detail.value == 2 && this.data.firstChange) {
      wx.showModal({
        title: '温馨提示',
        content: '如果您选择对公账号汇款，请在汇款的备注栏注明（经销商姓名或者订单编号后6位数字），以便核对。谢谢',
        showCancel: false
      })
      this.setData({
        firstChange: false
      })
    }
    this.setData({
      payType: e.detail.value
    })
  },

  async createOrder(e) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    var that = this;
    // var loginToken = app.globalData.token // 用户登录 token
    var remark = ""; // 备注信息
    if (e) {
      remark = e.detail.value.remark; // 备注信息
    }
    console.log(this.data.goodsList)

    if (!that.data.curAddressData) {
      wx.hideLoading();
      wx.showModal({
        title: '友情提示',
        content: '请先设置您的收货地址！',
        showCancel: false
      })
      return;
    }
    let type = this.data.orderType
    if (this.data.coupon) {
      let response = await chooseCoupon(type, this.data.coupon.id, true, wx.getStorageSync('access_token'))
      if (response && response.code == 10000) {

      } else {
        wx.showToast({
          title: response.msg,
          icon: 'none'
        })
      }
    }
    let response = await shippingAddress(this.data.curAddressData.id, type, wx.getStorageSync('access_token'))
    let res = await createTrade(type, wx.getStorageSync('access_token'))
    console.log(res)
    if (res && res.code == 10000) {
      wx.showToast({
        title: '订单提交成功',
        icon: 'success',
        duration: 1500,
        success: () => {
          setTimeout(function () {
            wx.redirectTo({
              url: '/pages/order-list/order-list?currentType=0'
            })
          }, 1500)
        }
      })
    }


    // if (that.data.curCoupon) {
    //   postData.couponId = that.data.curCoupon.id;
    // }
    // if (!e) {
    //   postData.calculate = "true";
    // }

    // app.postForm("order/insert_order", postData, (res) => {
    //   if (res && res.code == "0") {
    //     wx.removeStorageSync('shopCarInfo');
    //     wx.removeStorageSync('buykjInfo');
    //     wx.removeStorageSync('PingTuanInfo');
    //     wx.removeStorageSync('orderDetail');
    //     let payData = {
    //       OrderIds: res.result.OrderId,
    //       OpenId: app.globalData.openid,
    //       Type: 'JSAPI'
    //     }
    //     if (isDealer == 1) {

    //       app.postForm('dealer/update_dealer_orderid', {
    //         OrderId: res.result.OrderId,
    //         Id: that.data.dealerId
    //       }, res => {
    //         console.log(res)
    //       })
    //     }
    //     app.postForm('order/pay_order_by_orderids', payData, rep => {
    //       // console.log(rep)
    //       wx.hideLoading();
    //       if (that.data.payType == 1) {
    //         that.wxPay(rep)
    //       } else {
    //         wx.showToast({
    //           title: '订单已提交',
    //           icon: 'success',
    //           duration: 1000,
    //           success: () => {
    //             setTimeout(function () {
    //               wx.navigateBack({
    //                 delta: 1 //返回上一级页面
    //               })
    //             }, 1500)
    //           }
    //         })
    //       }
    //     })
    //   } else {
    //     wx.hideLoading();
    //     wx.showModal({
    //       title: '错误',
    //       content: res.msg,
    //       showCancel: false
    //     })
    //   }
    // })
  },


  wxPay(params) {
    // console.log(params)
    var that = this;
    wx.requestPayment({
      timeStamp: params.timeStamp,
      nonceStr: params.nonceStr,
      package: params.package,
      signType: 'MD5',
      paySign: params.paySign,
      success: function (res) {
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 1000,
          success: () => {
            setTimeout(function () {
              wx.navigateBack({
                delta: 1 //返回上一级页面
              })
            }, 1500)
          }
        })
      },
      fail: function (res) {
        wx.showToast({
          title: '已取消支付',
          icon: 'success',
          duration: 1500,
          // success: () => {
          //   setTimeout(function () {
          //     wx.navigateBack({
          //       delta: 1 //返回上一级页面
          //     })
          //   }, 1500)
          // }
        })
      },
      complete: function (res) {
        console.log(res);
      }
    })
  },
  async initShippingAddress() {
    var that = this
    let addressData = await getAddress(app.globalData.userInfo.id, 1, 100, wx.getStorageSync('access_token'))
    console.log(addressData)
    if (addressData.code == 10000) {
      this.setData({
        curAddressData: addressData.data.records[0],
        loadingMoreHidden: true
      })
    } else {
      that.setData({
        curAddressData: null
      })
    }
    // app.get("/user/get_address_by_custid?CustId=" + app.globalData.uid, (res) => {
    //   console.log(res);

    //   if (res && res.code == "0") {
    //     var addr = res.result.find(item => item.IsDefault == 1);
    //     if (res.result.length > 0) {
    //       if (addr) {
    //         addr.District = addr.District == "请选择" ? "" : addr.District;
    //       } else {
    //         addr = res.result[0]
    //         addr.District = addr.District == "请选择" ? "" : addr.District;
    //       }
    //       that.setData({
    //         curAddressData: addr
    //       });
    //     } else {
    //       that.setData({
    //         curAddressData: null
    //       })
    //     }
    //   }
    // });
  },
  processYunfei: function () {
    var that = this;
    var goodsList = this.data.goodsList;
    var goodsJsonStr = "[";
    var isNeedLogistics = 0;
    var allGoodsPrice = 0;

    for (let i = 0; i < goodsList.length; i++) {
      let carShopBean = goodsList[i];
      if (carShopBean.logistics) {
        isNeedLogistics = 1;
      }
      allGoodsPrice += carShopBean.price * carShopBean.number;

      var goodsJsonStrTmp = '';
      if (i > 0) {
        goodsJsonStrTmp = ",";
      }


      let inviter_id = 0;
      let inviter_id_storge = wx.getStorageSync('inviter_id_' + carShopBean.goodsId);
      if (inviter_id_storge) {
        inviter_id = inviter_id_storge;
      }


      goodsJsonStrTmp += '{"goodsId":' + carShopBean.goodsId + ',"number":' + carShopBean.number + ',"propertyChildIds":"' + carShopBean.propertyChildIds + '","logisticsType":0, "inviter_id":' + inviter_id + '}';
      goodsJsonStr += goodsJsonStrTmp;


    }
    goodsJsonStr += "]";
    //console.log(goodsJsonStr);
    that.setData({
      isNeedLogistics: isNeedLogistics,
      goodsJsonStr: goodsJsonStr
    });
    that.createOrder()
  },
  addAddress: function () {
    wx.navigateTo({
      url: "/pages/address-add/address-add"
    })
  },
  selectAddress: function () {
    wx.navigateTo({
      url: "/pages/address/address"
    })
  },


})